<template>
 <div>
    <fou-dialog :title="'套票報名'" v-model:dialogValue="ticdialog" :width="'60%'" ref="dialog" >
        <template #content>
        <div class="echarts">
          <div class="flex justify-center w-[100%]" style="font-size:25px;font-weight:700">套票使用</div>
           <el-form :model="form" label-position="left" label-width="120px"  ref="ruleFormRef" class="mt-[15px]" >
             <el-row :gutter="24">
                  <!-- <el-col :span="8">
                    <el-form-item label="套票" prop="student_id">
                        <el-button  @click="add" type="primary" circle icon="Search"></el-button>
                    </el-form-item>
                  </el-col> -->
                  <el-col :span="8">
                    選擇套票名字：{{ticketList?.name}}
                  </el-col>
                  <el-col :span="12">
                    未用數量：{{notusedNumber}}
                  </el-col>
                  <el-col :span="24" >
                    <el-form-item  label="课程  報讀課程：" prop="student_id" class="scrolls ">
                        <el-select  v-model="classroom_id"  size="default" style="width:430px" >
                          <el-option  v-for="item in ticketList?.course" :key="item.id" :label="item.name" :value="item.id" />
                        </el-select>
                        <el-button class="ml-[15px]"  @click="addcourse" type="primary" circle icon="Search"></el-button>
                    </el-form-item>
                  </el-col>
                <el-col :span="24">
                  <el-form-item label="日期" prop="rules_date" class="scrolls">
                        <date-controls :isFlash="false" ref="datecontrols" :defultValue="ticketList" :searchConfig="setFormConfig" @update="update" />
                  </el-form-item>
                </el-col>
             </el-row>
           </el-form>
        </div>
        <div class="echarts mt-[20px] ">
                    <ProTable
                :data="list"
                :page="{}"
                :column="columned"
                :rowControl="[]"
                :elProps="{border:true,selection:true,height:300}"
                :disabled="[]"
                :controlWidth="{  name:120,
                          number:120,
                          date:180,
                          time1:180,
                          teacher:120,
                          nums:120}"
                @selection-change="onSelectionChange"
                >
                </ProTable>
                <div class="flex justify-end mt-[15px]">
                  <el-button @click="register" style="color:#fff" color="#50BC58">登記</el-button>
                </div>
        </div>
        <div>
                              <ProTable
                :data="courseList"
                :page="{}"
                :column="columned"
                :rowControl="[]"
                :elProps="{border:true,selection:false,height:300}"
                :disabled="[]"
                :controlWidth="{ name:120,
                          number:120,
                          date:180,
                          time1:180,
                          teacher:120,
                          nums:120}"
                @selection-change="onSelectionChange"
                >
                <template #search_operate>
                    <el-table-column  fixed="right" min-width="50px" >
                        <template #default="scope">
                            <el-link class="flex justify-center" type="primary" :underline="false" @click="handleDelete(scope.row,scope.$index, )" >删除</el-link >
                        </template>
                    </el-table-column>
                </template>
                </ProTable>
        </div>

        </template>
        <template #footer>
            <div class="flex justify-center ">
                <el-button @click="ticdialog = false">取消</el-button>
                <el-button color="#081F42" @click="confirm">確定</el-button>
            </div>
        </template>
    </fou-dialog>
 </div>
</template>

<script setup>
import {ref,reactive} from 'vue'
import {getTickets,useTickets,checkTickets} from '@/http/index.js'
import {message} from '@/common/function.js'
import {setFormConfig} from './useticker.js'
import { dayjs } from "element-plus";
import isoWeekday from 'dayjs/plugin/isoWeek'
import isBetween from 'dayjs/plugin/isBetween'
dayjs.extend(isoWeekday)
dayjs.extend(isBetween)
const column = {
  name:'套票名字',
  number:'發票編號',
  num:'套票數量',
  useNum:'使用數量',
  create_time:'創建時間'
}
const columned = {
  name:'課程名稱',
  number:'課程編號',
  date:'日期',
  time1:'時間',
  teacher:'導師',
  nums:'上課人數'
}
const form = reactive({
    student_id:localStorage.getItem('student_id'),
});
const classroom_id = ref([])

const list = ref([])
const addcourse = ()=>{
  if (!classroom_id.value  ) {
    return message('請選擇報讀課程','warning')
  }
  if (!time.value  ||time.value.length < 1) {
    return message('請選擇日期','warning')
  }
  let equation = ticketList.value.course.find(item => classroom_id.value === item.id)
//   console.log(equation.start_time,equation.end_time);
//   console.log(time.value[0],'0');
//   console.log(time.value[1],'1');
//   console.log(dayjs(time.value[0]).isBetween(equation.start_time, dayjs(equation.end_time),null, '[['))
//  console.log(dayjs(time.value[1]).isBetween(equation.start_time, dayjs(equation.end_time),null, '[['));
  if (dayjs(time.value[0]).isBetween(equation.start_time, dayjs(equation.end_time),null, '[[')
  && dayjs(time.value[1]).isBetween(equation.start_time, dayjs(equation.end_time),null, '[[')) {
      let dateStart = dayjs(time.value[0]),
  dateEnd = dayjs(time.value[1]),
  dateDiff = dateEnd.diff(dateStart, 'days'),
  weekVal =equation.week.split(',').map(Number),
  newList = [],
  j = 0,
  chineseWeek = ['一', '二', '三', '四', '五', '六', '日'];
  let rules_time =  equation.time.split('-')[0]
        while (dateDiff >= j) {
            let num = dayjs(time.value[0]).add(j, 'days').isoWeekday()
          weekVal.forEach((v, i) => {
            if (v === num) {
              let obj = dayjs(dateStart).add(j, 'days')
              // console.log(obj);
              let strs = rules_time.split(':')
              let completeStartDate = dayjs(obj).add(parseInt(strs[0]), 'hours').add(parseInt(strs[1]), 'minutes')
                .format('YYYY-MM-DD HH:mm')
              let completeEndDate = dayjs(obj).add(parseInt(strs[0]), 'hours').add(parseInt(strs[1]) + parseInt(
                60), 'minutes').format('YYYY-MM-DD HH:mm')
              // return
              let formData = {
                ...equation
              }
              formData.time1 = `${completeStartDate.split(' ')[1]}-${completeEndDate.split(' ')[1]}`
              formData.date = `${dayjs(obj).format('YYYY-MM-DD')}(${chineseWeek[v-1]})`
              // formData.NumberPeople = `${formData.number}/${formData.maxNumber}`
              formData.start_time = `${completeStartDate}:00`
              formData.end_time = `${completeEndDate}:00`
              formData.type = '1'
            //   formData.status = formData.auditoriumStatus == '1' ? '試堂' : '未上課'
              formData.status  == '1' ? '欠款' : '未上課'
              delete formData.rules_date
              delete formData.rules_time
              newList.unshift(formData)
            }
          })
          j++
        }
        console.log(newList);
        console.log(ticketList.value.day);
        
        newList.map(e=>{
          e.nums = e.num
          e.num = 1
        })
        let a = newList.reverse().slice(0,ticketList.value.day)
        console.log(a);
        list.value = a
        return newList
  }else{
    message('所選課程不在可使用時間範圍','warning')
  }

}
// 多选
const selectList = ref([])
const onSelectionChange = (e)=>{
  // console.log(e);
  selectList.value = e
}
// 登记
const courseList = ref([])
const register = async()=>{
  if (selectList.value.length > notusedNumber.value) {
  return  message('報名數量超出已購套票數!','warning')
  }
  // selectList.value.map(e=>{
  //   e.nums = e.num
  //   e.num =1
  // })
  var now = dayjs().format('YYYY-MM-DD HH:mm:ss')
  console.log(now);
  let obj = {
    student_id:student_id.value,
    school_id:localStorage.getItem('school_id'),
    data:[],
  }
  obj.data = selectList.value
  const data = await checkTickets(obj)
  if (data.code == 200) {
    selectList.value.map(e=>{
      console.log(e);
    })
    courseList.value = selectList.value
  }
}

const ticdialog = ref(false)
const notusedNumber = ref(0)
const ticketList = ref({})
const student_id = ref('')

const init = (value,num,id)=>{
    // console.log(value);
    ticketList.value = value
    notusedNumber.value = num
    student_id.value = id
    ticdialog.value = true
    classroom_id.value = []
    list.value = []
    courseList.value = []
}

const emit = defineEmits(['update'])
const time = ref([])
const update = (e)=>{
time.value = e
}
const submitData = reactive({
    student_id:'',
    school_id:localStorage.getItem('school_id'),
    data:[],
})
const confirm = async()=>{
  if (courseList.value.length <1) {
   return message('請選擇報讀課程','warning')
  }
  submitData.student_id = student_id.value
  submitData.data = courseList.value
  console.log(submitData);
  const data = await useTickets(submitData)
  if (data.code == 200) {
   message('使用套票成功')
    emit('update')
   ticdialog.value = false
  }
}
defineExpose({
    init
})
</script>

<style scoped lang='less'>
.a{
    justify-content: space-between;
}
</style>